package com.develop;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.develop.BeanUtils.Message;
import com.develop.BeanUtils.MsgType;
import com.develop.BeanUtils.SharedStorage;
import com.develop.BusinessGatewayService.BusinessGatewayClient;
import com.develop.GatewayService.GatewayClient;
import com.develop.vo.AlarmMsgVo;

@SpringBootApplication
public class DevelopApplication implements CommandLineRunner {
	private static final Logger LOG = LoggerFactory.getLogger(DevelopApplication.class);
	ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2);

	public static void main(String[] args) {
		if (args.length == 0 || args.length != 9) {
			throw new IllegalArgumentException("传入参数错误！参数格式为：(业务网关连接ip,业务网关连接端口,城市编码英文缩写,厂家编码英文缩写,OMC类型标识,网关连接ip,网关连接端口,用户名,密码)");
		}
		SpringApplication.run(DevelopApplication.class, args);

		Runtime.getRuntime().addShutdownHook(new Thread() {
			@Override
			public void run() {
				AlarmMsgVo alarmMsgVo = Message.generateMessage((byte) MsgType.closeConnAlarm.getIndex(), MsgType.closeConnAlarm + "");
				SharedStorage.getGatewayClient().writeAndFlush(alarmMsgVo);
				SharedStorage.getGatewayClient().close();
				LOG.info("向OMC发送关闭连接消息.");
				SharedStorage.getBusinessGatewayClientChannel().close();
				LOG.info("向业务网关发送关闭通道消息.");
			}
		});
	}

	@Override
	public void run(String... args) throws Exception {
		fixedThreadPool.execute(() -> {
			String host = args[0];
			int port = Integer.parseInt(args[1]);
			String cityCode = args[2];
			String firmCode = args[3];
			String omcType = args[4];
			try {
				new BusinessGatewayClient(host, port, cityCode, firmCode, omcType).start();
			} catch (Exception e) {
				e.printStackTrace();
			}
		});

		fixedThreadPool.execute(() -> {
			String host = args[5];
			int port = Integer.parseInt(args[6]);
			String user = args[7];
			String password = args[8];
			try {
				new GatewayClient(host, port, user, password).start();
			} catch (Exception e) {
				e.printStackTrace();
			}
		});
	}
}
